
using System.Text;
using System;
using System.Diagnostics;
using TfsAlert.Core.WorkflowServices;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using TfsAlert.Core;
using TfsAlert.Workflows;

namespace Microsoft.Services.TfsAlert.AppCode.NotificationEvents
{
    public partial class BuildCompletionEvent : BaseNotificationEvent
    {
        #region INotificationEvent Members

        public override string GetNotificationMessage()
        {
            StringBuilder stringMessageBuilder = new StringBuilder();

            stringMessageBuilder.AppendLine( "Title: " + this.Title );
            stringMessageBuilder.AppendLine( "Requested By: " + this.RequestedBy );
            stringMessageBuilder.AppendLine( "Build Configuration: " + this.Configuration );
            stringMessageBuilder.AppendLine( "Build Configuration: " + this.Url);

            if ( 0 == String.Compare( "FAILED", this.CompletionStatus, true ) || 0 == String.Compare( "Partially Succeeded", this.CompletionStatus, true ) )
                BuildCompletionWorkflow.RelayOn();
            else
                BuildCompletionWorkflow.RelayOff();

            return stringMessageBuilder.ToString();
        }

        public override Strings.BuildStatus GetBuildStatus()
        {
            switch ( this.CompletionStatus.ToUpper() )
            {
                case "FAILED":
                    return Strings.BuildStatus.Failed;
                case "Partially Succeeded":
                    return Strings.BuildStatus.PartiallySucceeded;
                case "Aborted":
                    return Strings.BuildStatus.Aborted;
                default:
                    return Strings.BuildStatus.Success;
            }
        }

        #endregion
       
    }

    public static class BuildCompletionWorkflow
    {
        static RelayService relayService = new RelayService( 3 );
        static WorkflowInstance wfInstance = null;

        static BuildCompletionWorkflow()
        {
            WorkflowRuntime wfRuntime = WorkflowFactory.GetWorkflowRuntime();
           
            ExternalDataExchangeService dataService = new ExternalDataExchangeService();
            wfRuntime.AddService( dataService );
            dataService.AddService( relayService );

            wfInstance = wfRuntime.CreateWorkflow( typeof( RS232 ) );
            wfInstance.Start();

            relayService.InstanceId = wfInstance.InstanceId;
        }
        
        public static void RelayOn()
        {
            relayService.RelayOn();
        }

        public static void RelayOff()
        {
            relayService.RelayOff();
        }
    
    }
}